package org.example.myleet.rosalind.lexf;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        String path = solution.getClass().getResource("").getPath();
        solution.printAllOrder("A B C D E F G", 3, path);
    }

    public void printAllOrder(String tokens, int n, String path) {
        path += "output.txt";
        String[] alphabet = tokens.split(" ");
        File outputFile = new File(path);
        if (outputFile.exists()) {
            outputFile.delete();
        }
        OutputStream os = null;
        try {
            outputFile.createNewFile();
            os = new FileOutputStream(outputFile);
            dfs("", n, alphabet, os);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void dfs(String order, int n, String[] alphabet, OutputStream os) throws IOException {
        if (order.length() == n) {
            os.write(order.getBytes());
            os.write("\n".getBytes());
            return;
        }
        for (int i = 0; i < alphabet.length; ++i) {
            dfs(order + alphabet[i], n, alphabet, os);
        }
    }
}
